<?php

class Admin extends Admin_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model("Admin_m");
        $this->_data['sidebar'] = "user";
        $this->load->library('formdate');
    }

    public function index() {
        $this->login();
    }

    public function login() {
        if ($this->session->userdata('admin_id') != "") {
            redirect('thanh_toan/danh_sach_chua_thanh_toan');
        }

        $config = array(
            array("field" => "email",
                "label" => lang("email"),
                "rules" => "required|valid_email|xss_clean"
            ),
            array("field" => "password",
                "label" => lang("password"),
                "rules" => "required|xss_clean"
            )
        );
        $this->form_validation->set_rules($config);
        if ($this->input->post("submit")) {
            //form validation true
            if ($this->form_validation->run()) {
                //check valid email and password
                $email = $this->input->post("email");
                $password = md5($this->input->post("password"));

                $query = $this->Admin_m->_check_valid_login($email, $password);
                $countUser = $query->num_rows();

                if ($countUser == 1) {//valid email and password
                    //set session
                    $user_infor = $this->Admin_m->_get_user_infor($email)->row();
                    $user_id = $user_infor->id;
                    $email = $user_infor->email;
                    $hoten = $user_infor->ho_ten;
                    $role = $user_infor->id_role;

                    $this->session->set_userdata("admin_id", $user_id);
                    $this->session->set_userdata("admin_email", $email);
                    $this->session->set_userdata("admin_name", $hoten);
                    $this->session->set_userdata("admin_role", $role);


                    //load admin panel
                    redirect('thanh_toan/danh_sach_chua_thanh_toan');
                } else {//wrong email or password
                    $_data['login_error'] = "Sai e-mail hoặc mật khẩu";
                    $this->load->view("admin/users/login", $_data);
                }
            } else {
                //form validation fail
                $this->load->view("admin/users/login");
            }
        } else {
            $this->load->view("admin/users/login");
        }
    }

    //--logout--//
    function logout() {
        is_admin();
        //check session != null
        //unset session
        //redirect login page
        if ($this->session->userdata("admin_id") != NULL) {
            $this->session->unset_userdata("admin_id");
            $this->session->unset_userdata("admin_role");
            $this->session->unset_userdata("admin_name");
            redirect("admin/login");
        } else {
            redirect("admin/login");
        }
    }

    //--list users--//
    public function users() {
        is_admin();
        $this->_data['page_title'] = "danh sách người dùng";
        $perpage = $this->uri->segment(3);
        $offset = $this->uri->segment(4);
        if ($perpage == "") {
            $perpage = 10; //10 records per page
        }
        if ($offset == "") {
            $offset = "";
        }
        $config['base_url'] = base_url() . "index.php/admin/users/" . $perpage . "/";
        $config['per_page'] = $perpage;
        $config['uri_segment'] = 4;
        $config['total_rows'] = $this->Admin_m->_count_users();
        if ($offset > 0 && $offset == $config['total_rows']) {
            $offset = $offset - $perpage;
        }
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();
        $this->_data['total'] = $config['total_rows'];
        $this->_data['perpage'] = $perpage;
        $this->_data['offset'] = $offset;

        $query = $this->Admin_m->_get_users($perpage, $offset);

        $this->_data['users_data'] = $query;
        $this->display_admin("admin/users/list_admin");
    }

    //--Add new user--//
    public function tao_user() {
        is_admin();
        $this->_data['page_title'] = "Tạo mới user"; //page title
        // validate form config
        $config = array(
            array("field" => "ho_ten",
                "label" => "Họ tên",
                "rules" => "required|trim|xss_clean"
            ),
            array("field" => "email",
                "label" => "Email",
                "rules" => "required|trim|xss_clean|valid_email|callback__check_exist_field[users.email]"
            ),
            array("field" => "password",
                "label" => "Password",
                "rules" => "required|trim|xss_clean|min_length[5]|callback__check_matches_password"
            ),
            array("field" => "confirm_password",
                "label" => "Nhập lại password",
                "rules" => "required|trim|xss_clean"
            ),
            array("field" => "roles",
                "label" => 'loại',
                "rules" => "xss_clean"
            ),
        );
        $this->form_validation->set_rules($config); //set validation rules

        if ($this->input->post("submit")) {

            //if validate form OK add data to database
            //else re-load form and show errors
            if ($this->form_validation->run() === TRUE) {
                //Add to user table

                $password = md5($this->input->post("password"));
                $role_id = $this->input->post("role");

                $query_add_user = $this->Admin_m->add_user(array("password" => $password,
                    "id_role" => $role_id)
                );

                if ($query_add_user) {
                    $this->session->set_flashdata('error', 'Thêm mới thành công');
                    redirect("admin");
                } else {
                    $this->session->set_flashdata('error', 'Thêm mới thất bại');
                    redirect("admin");
                }
            } else {
                $this->display_admin('admin/users/add_user');
            }
        } else {
            $this->display_admin('admin/users/add_user');
        }
    }

    //--edit profile--//
    //user only can edit his/her own account
    //user can see but not edit profile of other users
    function modifier_profile($id) {
        is_admin();
        $this->_data['page_title'] = "modifier profile";
        $this->load_profile($id, TRUE);

        //validate form config
        $config = array(
            array("field" => "first_name",
                "label" => lang("first_name"),
                "rules" => "required|trim|xss_clean"
            ),
            array("field" => "last_name",
                "label" => lang("last_name"),
                "rules" => "required|trim|xss_clean"
            ),
            array("field" => "telephone",
                "label" => lang("telephone"),
                "rules" => "trim|xss_clean"
            ),
            array("field" => "telephone",
                "label" => lang("mobilephone"),
                "rules" => "trim|xss_clean"
            ),
            array("field" => "gender",
                "label" => lang("gender"),
                "rules" => "trim|xss_clean"
            ),
        );
        $this->form_validation->set_rules($config); //set validation rules
        //if submit button clicked
        //process form
        //else reload form

        if ($this->input->post("submit")) {
            //validation ok
            if ($this->form_validation->run() === TRUE) {
                $dob_day = $this->input->post("day");
                $dob_month = $this->input->post("month");
                $dob_year = $this->input->post("year");
                $dob_bigint = mktime("0", "0", "0", $dob_month, $dob_day, $dob_year); //convert datetime to bigint

                $query = $this->Admin_m->edit_user(array("DOB" => $dob_bigint, "gender" => $this->input->post("gender")), $id);
                if ($query) {
                    $this->session->set_flashdata("error", lang("edit_profile") . " Profile " . lang("success"));
                    redirect("admin");
                } else {
                    $this->session->set_flashdata("error", lang("edit_profile") . " Profile " . lang("fail"));
                    redirect("admin");
                }
            } else {//validation false
                $this->display_admin('admin/users/edit_profile');
            }
        } else {
            $this->display_admin('admin/users/edit_profile');
        }
    }

    //--view user profile--//
    function view_profile($id) {
        is_admin();
        $this->_data['page_title'] = "Profile";
        $this->load_profile($id, FALSE);
        $this->display_admin('admin/users/view_profile');
    }

    //--load user profile--//
    function load_profile($id, $to_edit = FALSE) {
        if (!isset($id) && ($id == NULL)) {
            redirect("admin");
        } else {
            if ($this->Admin_m->_get_user_id($id) === FALSE) {
                redirect("admin");
            } elseif ($to_edit === TRUE) {
                if ($id != $this->session->userdata("admin_id")) {
                    redirect("admin");
                }
            }
        }
        //load exist data to form
        $profile_data = $this->Admin_m->get_user_profile($id);
        $data = $this->_data['profile_data'] = $profile_data->row();

        //load company
        $company = $data->company;
        $this->_data['company'] = $company;

        //dropdown companies 
        $dd_roles = $this->Admin_m->_get_dd_data('company');
        $this->_data['dd_company'] = $dd_roles;

        //create dropdown date time
        $dob_bigint = $data->DOB;
        $datestring = "%Y-%m-%d";
        $dob_arr = mdate($datestring, $dob_bigint);
        $dob_human = explode("-", $dob_arr);

        $formdate = new FormDate();
        $formdate->setLocale(LC_TIME, 'fr_FR.utf8', 'fra');
        //year
        $formdate->year['start'] = 1940;
        $formdate->year['end'] = 2040;
        $formdate->year['selected'] = $dob_human[0];
        $formdate->year['extra'] = 'class="short"';
        //month
        $formdate->month['values'] = 'names';
        $formdate->month['selected'] = $dob_human[1];
        $formdate->month['extra'] = 'class="short"';
        //day
        $formdate->day['selected'] = $dob_human[2];
        $formdate->day['extra'] = 'class="short"';

        $this->_data['formdate'] = $formdate;

        //gender
        $dd_gender = array("1" => "male", "2" => "female");
        $this->_data['dd_gender'] = $dd_gender;
        $gender = $data->gender;
        $this->_data['gender'] = "";
        if ($gender == 1) {
            $this->_data['gender'] = "Male";
        } elseif ($gender == 2) {
            $this->_data['gender'] = "FeMale";
        }
    }

    //--change active status--//
    function changement($id) {
        is_admin();
        $active_status = $this->Admin_m->_check_active_status($id)->row();
        if ($active_status->active == 1) {
            $data = array("active" => 0);
        } elseif ($active_status->active == 0) {
            $data = array("active" => 1);
        }
        $this->Admin_m->update_active_status($data, $id);
        redirect("admin");
    }

    //--change password--//
    function change_password($id) {
        is_admin();
        $this->_data['page_title'] = "Change Password";
        

        $config = array(
            array("field" => "old_pass",
                "label" => "Password hiện tại",
                "rules" => "required|trim|xss_clean|callback__check_old_password"
            ),
            array("field" => "new_password",
                "label" => "Password mới",
                "rules" => "required|trim|xss_clean|min_length[5]|callback__check_matches_password"
            ),
            array("field" => "confirm_password",
                "label" => "Nhập lại password mới",
                "rules" => "required|trim|xss_clean"
            )
        );
        $this->form_validation->set_rules($config);

        if ($this->input->post("submit")) {
            if ($this->form_validation->run()) {
                $data = array("password" => md5($this->input->post("new_password")));
                $query = $this->Admin_m->change_password($data, $id);
                if ($query) {
                    $this->session->set_flashdata("error", "Đổi mật khẩu thành công");
                    redirect("khach_hang");
                } else {
                    $this->session->set_flashdata("error", "Đổi mật khẩu thất bại");
                    redirect("khach_hang");
                }
            } else {
                $this->display_admin('admin/users/change_password');
            }
        } else {
            $this->display_admin('admin/users/change_password');
        }
    }

    //--delete user--//
    //only super admin can delete
    function xoa_user($id) {
        is_admin();
        $query = $this->Admin_m->delete_user($id);
        if ($query === TRUE) {
            $this->session->set_flashdata("error", "Xóa thành công");
            redirect("admin");
        }else{
            $this->session->set_flashdata("error", "Xóa thất bại");
            redirect("admin");
        }
    }

    //check exist field from db
    //if exist return FALSE
    //else return TRUE
    function _check_exist_field($str, $param) {
        $arr = explode(".", $param);
        $query = $this->Admin_m->_get_field_input($arr[0], $arr[1], $str);
        if ($query) {
            $this->form_validation->set_message("_check_exist_field", "%s existe");
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function _check_dropdown($str) {
        if ($str == -1) {
            $this->form_validation->set_message("_check_dropdown", "Vous devez choisir le %s");
            return FALSE;
        } else {
            return TRUE;
        }
    }

    //check if password = confirm_password
    // = return True
    // != return FALSE
    function _check_matches_password($str) {
        $confirm_password = $this->input->post("confirm_password");
        if ($str != $confirm_password) {
            $this->form_validation->set_message("_check_matches_password", "2 password không giống nhau");
            return FALSE;
        } else {
            return TRUE;
        }
    }

    //check old password
    function _check_old_password($str_password) {
        $password = md5($str_password);
        $id = $this->session->userdata("admin_id");
        if ($this->Admin_m->get_old_password($password, $id)->num_rows() > 0) {
            return TRUE;
        } else {
            $this->form_validation->set_message("_check_old_password", "Password cũ không đúng");
            return FALSE;
        }
    }

}